package com.wangzhixuan.commons.utils;

import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Service
public class DBUtils {
	Logger logger=LoggerFactory.getLogger(getClass());
	
	@Autowired
	private DataSourceTransactionManager transactionManager;
	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;

	public int insert(String statement) {
		return sqlSessionTemplate.insert(statement);
	}

	public int insert(String statement, Object parameter) {
		return sqlSessionTemplate.insert(statement, parameter);
	}

	public int delete(String statement) {
		return sqlSessionTemplate.delete(statement);
	}

	public int delete(String statement, Object parameter) {
		return sqlSessionTemplate.delete(statement, parameter);
	}

	public int update(String statement) {
		return sqlSessionTemplate.update(statement);
	}
	public int update(String statement, Object parameter) {
		return sqlSessionTemplate.update(statement, parameter);
	}

	
	public <T> T selectOne(String statement) {
		return sqlSessionTemplate.selectOne(statement);
	}

	public <T> T selectOne(String statement, Object parameter) {
		return sqlSessionTemplate.selectOne(statement, parameter);
	}

	public <E> List<E> selectList(String statement) {
		return sqlSessionTemplate.selectList(statement);
	}

	public <E> List<E> selectList(String statement, Object parameter) {
		return sqlSessionTemplate.selectList(statement, parameter);
	}

	public TransactionStatus getTxStatus() {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);// 事物隔离级别，开启新事务
		TransactionStatus txStatus = transactionManager.getTransaction(def);// 获得事务状态
		return txStatus;
	}

	public void commitTx(TransactionStatus txStatus) {
		transactionManager.commit(txStatus);
	}

	public void rollbackTx(TransactionStatus txStatus) {
		transactionManager.rollback(txStatus);
	}
	
}
